package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;
//    @Autowired
//    private IVoucherOrderService proxy;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    private static final ExecutorService SECKILL_ORDER_EXCUTER = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {

        SECKILL_ORDER_EXCUTER.submit(new VoucherOrderHandle());
    }

    private class VoucherOrderHandle implements Runnable {
        @Override
        public void run() {
            while (true) {

                try {
                    //获取消息队列的订单 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 streams streams.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2000)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    //判断是否成功
                    if (list == null || list.isEmpty()) {
                        continue;
                    }
                    //成功创建订单
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value =entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(),true);
                    handleVoucherOrder(voucherOrder);
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",entries.getId());


                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();

                }

            }

        }


    }
    private void handlePendingList() {

        while (true) {
            try {
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders",ReadOffset.from("0"))
                );
                if (list.isEmpty() || list == null) {
                    break;
                }
                MapRecord<String, Object, Object> entries = list.get(0);
                Map<Object, Object> value =entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(),true);
                handleVoucherOrder(voucherOrder);
                stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",entries.getId());
            } catch (Exception e) {
                log.error("处理异常", e);
            }

        }

    }
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
//    private class VoucherOrderHandle implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//
//                try {
//                    //获取订单
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //创建订单
//                    handleVoucherOrder(voucherOrder);
//
//
//                } catch (InterruptedException e) {
//                    log.error("处理订单异常", e);
//                }
//
//            }
//
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {

        long userId = voucherOrder.getUserId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);

        boolean islock = false;
        try {
            islock = lock.tryLock(1,1200L, TimeUnit.SECONDS);
            if(!islock){
                log.error("获取锁失败");
                return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
             proxy.creatVoucher(voucherOrder);
        } finally {
            if (islock) {
                lock.unlock();
            }
        }

    }

    @Override
    public Result secKillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();

        long orderId = redisIdWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        //判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r==1?"库存不足":"不能重复下单");

        }

        this.proxy = (IVoucherOrderService) AopContext.currentProxy();
        //为0则代表有购买资格写入阻塞队列

        //TODO 保存到阻塞队列

        return Result.ok(orderId);

    }

//        @Override
//    public Result secKillVoucher(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(),
//                userId.toString()
//        );
//        //判断结果是否为0
//        int r = result.intValue();
//        if (r != 0) {
//            return Result.fail(r==1?"库存不足":"不能重复下单");
//
//        }
//        //为0则代表有购买资格写入阻塞队列
//        long orderId = redisIdWorker.nextId("order");
//        //TODO 保存到阻塞队列
//        //创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //获取id
//        long id = redisIdWorker.nextId("order");
//        voucherOrder.setId(id);
//
//        voucherOrder.setUserId(userId);
//        //代金券id
//        voucherOrder.setVoucherId(voucherId);
//
//       // proxy = (IVoucherOrderService) AopContext.currentProxy();
//        try {
//            orderTasks.put(voucherOrder);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//
//
//        return Result.ok(orderId);
//
//    }
//    @Override
//    public Result secKillVoucher(Long voucherId) {
//
//        //查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
//        //判断是否开始
//        LocalDateTime now = LocalDateTime.now();
//        if(now.isBefore(voucher.getBeginTime())){
//            return Result.fail("活动尚未开始!");
//        }
//        if(now.isAfter(voucher.getEndTime())){
//            return Result.fail("活动已经结束!");
//        }
//        //判断库存够不够
//        if(voucher.getStock() < 1){
//            return Result.fail("库存不足!");
//        }
//
//        Long userId = UserHolder.getUser().getId();
//
//      //  SimpleRedisLock lock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//
//        boolean islock = false;
//        try {
//            islock = lock.tryLock(1,1200L, TimeUnit.SECONDS);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        if(!islock){
//            return Result.fail("一个用");
//        }
//        try {
//            //获取代理对象事务
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//            return proxy.creatVoucher(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//
//    }

    @Transactional(rollbackFor = Exception.class)
    public void creatVoucher(VoucherOrder voucherOrder) {
        //用户id
        Long userId = voucherOrder.getUserId();
        long voucherId = voucherOrder.getVoucherId();
            //判断是否存在
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if(count > 0){
                return;
            }
            //扣减库存
            boolean result = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if(!result){
                log.error("库存不足");
            }


            //保存数据库
            save(voucherOrder);



    }

}
